import React,{Component}from 'react';
import { View, Text ,InteractionManager,DeviceEventEmitter,NativeModules} from "react-native";
import {WebView} from 'react-native-webview';
import Constants from '../common/Constants';
import UserManager from "../common/UserManager";
export default class WebviewPage extends Component{

    constructor(props) {
        super(props);
        this.state = {
            show: false,
            webview: null,
            userInfo: {},
            longTicket: '',
        };
        this.webViewRef= React.createRef();

        this.getDefaultValue()
       
    }

    async getDefaultValue(){
        let user = await UserManager.getUserInfo()
  
        this.setState({userInfo: user})
      
        let longTicket = await  UserManager.getLongTicket()
        this.setState({longTicket: longTicket})


    }
    componentDidMount() {

        /**
     * 主要是在执行动画时，避免执行其他工作量比较大的代码，
     * 比如，最好不要一边渲染，一边执行动画，而是先执行动画，
     * 等动画执行结束后在渲染，可以setTimeout来延时执行渲染，最好是用官方推荐的做法，利用InteractionManager
     */
        InteractionManager.runAfterInteractions(() => {
            this.setState({show: true});
        });

       

        
    }


    componentWillUnmount(){
      DeviceEventEmitter.removeAllListeners('didGetRFID')
    
    }

    scanCodeFn(data){

        // alert("scanCodeFn")
        alert(data.title)
    }
    
    handleMessage(event){
      const that = this
    
      console.log(event.nativeEvent);

      DeviceEventEmitter.addListener('didGetRFID',(res)=>{
       
        console.log("rn didGetRFID:", res)
        if(that.webViewRef !== null){
          const webJsonObj =  res
          console.log("rn bridgeApi didGetRFID:", res)
          const jsString = "window.bridgeApi && window.bridgeApi.didGetRFID('"+ webJsonObj +"');";
          that.webViewRef.injectJavaScript(jsString);
        }

      })

      //   const code = "123456789"

      //   const jsString = "H5BridgeApi.scanCodeResult && H5BridgeApi.scanCodeResult("+ code +");";

        var data = JSON.parse(event.nativeEvent.data)

        if(data.type === 'getUserInfo'){

          //获取用户信息
          // alert(data.type)

          const webJsonObj =  "{url: 'http://10.1.8.51:6060/Server.svc/api/invoke',userName: '" + this.state.userInfo.UserName + "',userId: '" + this.state.userInfo.UserId +"',orgId: '" + this.state.userInfo.InvOrg+ "',ticket: '" + this.state.longTicket + "'}";
          // alert (webJsonObj);
          const jsString = "bridgeApi.H5BridgeGetUserInfoResult && bridgeApi.H5BridgeGetUserInfoResult("+ webJsonObj +");";
          that.webViewRef.injectJavaScript(jsString);
        }else if(data.type === 'scanCode'){

          if(that.webViewRef !== null){

          

            this.props.navigation.navigate('DefaultScanCodePage', {callBack:(res)=>{
              const webJsonObj =  res
              // alert (webJsonObj);
              // alert ( that.webViewRef);
              const jsString = "bridgeApi && bridgeApi.H5BridgeScanCodeResult('"+ webJsonObj +"');";
              that.webViewRef.injectJavaScript(jsString);
            }});

           
          }
       
          
        }else if(data.type === 'startScanRFID'){

          if(that.webViewRef !== null){
           
            NativeModules.RFIDModule.startScanRFID((res)=>{
              console.log("rn startScanRFID:", res)
                const jsString = "window.bridgeApi && window.bridgeApi.didGetRFID('"+ res +"');";
                that.webViewRef.injectJavaScript(jsString);
            
            }, (err)=>{
              console.log("rn startScanRFID err:", err)
            })
           
          }
       
          
        }else if(data.type === 'stopScanRFID'){

          if(that.webViewRef !== null){
            NativeModules.RFIDModule.stopScanRFID((res)=>{

            }, (err)=>{
      
            })

           
          }
       
          
        }else if(data.type == 'closeApp'){
          
          this.props.navigation.goBack()
        }
      

    }


    render(){

        const item = this.props.route.params.item;
        var targetPath = "file:///" + Constants.documentPath + "/" + item.appId + "/" + item.appHisId + '/index.html';
      
        // var targetPath = "file:///" + item.localPath + '/index.html';
        // var targetPath =  "http://192.168.34.58:8081/proj/check_code/dist/index.html";
        // var targetPath =  "http://192.168.34.58:8081/projects/check_code/dist/index.html";
        // alert(targetPath)
        // var targetPath =  "http://192.168.34.58:8080/index.html";
        const strObj = `{url: '${Constants.serverUrl}:${Constants.serverPort}/Server.svc/api/invoke',userName: '${this.state.userInfo.UserName}',userId: '${this.state.userInfo.UserId}',orgId: '${this.state.userInfo.InvOrg}',ticket: '${this.state.longTicket }', isRNProject: true}`
      
        // alert(strObj)

        // const webJsonObj =  "{url: 'http://10.1.8.51:6060/Server.svc/api/invoke',userName: '" + this.state.userInfo.UserName + "',userId: '" + this.state.userInfo.UserId +"',orgId: '" + this.state.userInfo.InvOrg+ "',ticket: '" + this.state.longTicket + "'}";
        // alert (webJsonObj);
        const jsString = `getUserInfoSuccess && getUserInfoSuccess(${strObj})`;
      
        const H5AppBridge = `window.H5AppBridge = {
          callScanCode: function(data){
            let objData = {};
            objData.type = 'scanCode';
            objData.data = data;
            window.ReactNativeWebView.postMessage(JSON.stringify(objData));
          } ,
          callStartScanRFID: function(data){
            let objData = {};
            objData.type = 'startScanRFID';
            objData.data = data;
            window.ReactNativeWebView.postMessage(JSON.stringify(objData));
          } ,
          callStopScanRFID: function(data){
            let objData = {};
            objData.type = 'stopScanRFID';
            objData.data = data;
            window.ReactNativeWebView.postMessage(JSON.stringify(objData));
          } ,

          callSetNavTitle: function(data){
            let objData = {};
            objData.type = 'setNavTitle';
            objData.data = data;
            window.ReactNativeWebView.postMessage(JSON.stringify(objData));
          },
          callCloseApp: function(data){
            let objData = {};
            objData.type = 'closeApp';
            objData.data = data;
            window.ReactNativeWebView.postMessage(JSON.stringify(objData));
          }, 
          callGetUserInfo: function(data){
            let objData = {};
            objData.type = 'getUserInfo';
            objData.data = data;
            window.ReactNativeWebView.postMessage(JSON.stringify(objData));
          }
        };`

       


        const that = this
      

        return (
            this.state.show && (
                <View style={{flex: 1}}>
                  <WebView
                    ref={(ref)=>{ 

                            if(ref != null){
                                this.webViewRef = ref
                                
                            
                            }
                        }
                    }
            
                    style={{flex: 1,marginTop: 0}}
                    originWhitelist={['file://', 'http://', 'https://']}
                    injectedJavaScript={H5AppBridge}
                    source={{uri: targetPath}}
                    javaScriptEnabled={true}
                    allowUniversalAccessFromFileURLs={true}
                    allowFileAccess={true}
                    useWebKit = {true}
                    messagingEnabled={true}
          
                    domStorageEnabled={true}
                    renderError={() => {
                      alert("onLoadError")
                    }}
                    onLoadEnd={() => {
          
                      // alert(this.webViewRef)
                     this.webViewRef.injectJavaScript(jsString);
                      this.webViewRef.injectJavaScript(H5AppBridge);
                    }}
                    onMessage={event=>{
                        that.handleMessage(event)
                    }
          
                    }
                    onLoadStart={()=>{
                      this.webViewRef.injectJavaScript(H5AppBridge);
                      this.webViewRef.injectJavaScript(jsString);
                    }}
                  />
                </View>
              )

        );
    }
}